﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using Chire.ChireInter.Students;
using Chire.wechat;

namespace Chire.ChireInter.Work
{
    public class Work_Action
    {

        #region 添加作业
        /// <summary>
        /// 
        /// </summary>
        /// <param name="workList">传过来的作业列表</param>
        /// <param name="type">1给班级布置作业，2给个人布置作业</param>
        /// <param name="pushUser">type==1 班级id type == 2 个人id</param>
        /// <param name="hasPush">bool 是否推送</param>
        public void addWork(List<string> workList, int pushType, List<string> pushUser, int hasPush)
        {
            // 1. 生成随机编号
            string linkId = getRandomStr(11);
            // 2. 插入sub列表
            for (int i = 0; i < workList.Count; i++) {
                string workSingleStr = workList[i];
                addSubWork(workSingleStr, linkId);
            }

            // 3.1 获取当前的名字str
            string pushUserStr = "";
            for (int i = 0; i < pushUser.Count; i++) {
                string single = pushUser[i];
                if (i == pushUser.Count - 1)
                {
                    pushUserStr = pushUserStr + single;
                }
                else {
                    pushUserStr = pushUserStr + single + ",";
                }
            }

            // 3. 插入当前信息
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into work(workName,hasPush,pushType,pushUser,date,linkId) values(@workName,@hasPush,@pushType,@pushUser,@date,@linkId)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            // 1. 作者id
            cmd.Parameters.Add("@workName", SqlDbType.VarChar, 150);
            cmd.Parameters["@workName"].Value = DateTime.Now.ToShortDateString() + "日语作业";

            // 1. 作者id
            cmd.Parameters.Add("@hasPush", SqlDbType.VarChar, 50);
            cmd.Parameters["@hasPush"].Value = hasPush;

            // 2. 
            cmd.Parameters.Add("@pushType", SqlDbType.VarChar, 50);
            cmd.Parameters["@pushType"].Value = pushType;

            cmd.Parameters.Add("@pushUser", SqlDbType.VarChar, 50);
            cmd.Parameters["@pushUser"].Value = pushUserStr;

            cmd.Parameters.Add("@date", SqlDbType.VarChar, 50);
            cmd.Parameters["@date"].Value = DateTime.Now.ToString();

            cmd.Parameters.Add("@linkId", SqlDbType.VarChar, 50);
            cmd.Parameters["@linkId"].Value = linkId;
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();



            // 判断给学生推作业
            Student_Action studentAction = new Student_Action();
            string workStr = "\r";
            for (int i = 0 ; i < workList.Count;i++){
                string info = workList[i];
                if (i == workList.Count - 1){
                    workStr = workStr + info;
                } else {
                    workStr = workStr + info + "\r";
                }
            }

            if (pushType == 1) {        // 班级
                // 1. 获取班级1
                for (int c = 0; c < pushUser.Count; c++) {
                    string classId = pushUser[c];
                    List<Student_Model> studentList = studentAction.getAllStudent("1", classId);
                    for (int i = 0; i < studentList.Count; i++)
                    {
                        Student_Model studentModel = studentList[i];
                        addStudentWork(studentModel.id, linkId);

                        // 1. 
                        if (hasPush == 1)
                        {
                            pushWork(studentModel.id, workStr);
                        }
                    }
                }
            }
            else if (pushType == 2) {   // 学生
                // 2. 获取学生1
                for (int s = 0; s < pushUser.Count; s++) {
                    string studentId = pushUser[s];
                    Student_Model studentModel = studentAction.getStudentInfoWithId(studentId);
                    addStudentWork(studentModel.id, linkId);

                    // 1. 
                    if (hasPush == 1)
                    {
                        pushWork(studentModel.openid, workStr);
                    }
                }
            }
        }

        // 1. 插入分页信息
        private void addSubWork(string title, string linkId)
        {
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into work_sub(title,linkId) values(@title,@linkId)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            // 1. 作者id
            cmd.Parameters.Add("@title", SqlDbType.VarChar, 50);
            cmd.Parameters["@title"].Value = title;

            // 1. 作者id
            cmd.Parameters.Add("@linkId", SqlDbType.VarChar, 50);
            cmd.Parameters["@linkId"].Value = linkId;
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }

        // 2. 插入学生作业
        private void addStudentWork(string studentId,string linkId){
            // 连接数据库
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();
            string StrInsert = "";
            StrInsert = "insert into work_student(student_id,linkId,datetime) values(@student_id,@linkId,@datetime)";
            SqlCommand cmd = new SqlCommand(StrInsert, sqlcon);
            // 添加参数并且设置参数值
            // 1. 作者id
            cmd.Parameters.Add("@student_id", SqlDbType.VarChar, 50);
            cmd.Parameters["@student_id"].Value = studentId;

            // 1. 作者id
            cmd.Parameters.Add("@linkId", SqlDbType.VarChar, 50);
            cmd.Parameters["@linkId"].Value = linkId;

            cmd.Parameters.Add("@datetime", SqlDbType.VarChar, 50);
            cmd.Parameters["@datetime"].Value = DateTime.Now.ToString();
            // 执行插入数据的操作
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }
        #endregion

        #region 推送作业
        public void pushWork(string openId,string work) {
            Wechat_AccessToken wechatToken = new Wechat_AccessToken();

            WechatModelData first = new WechatModelData();
            first.value = "你有新的作业，请查收";
            first.color = "#6595A4";

            WechatModelData keyword1 = new WechatModelData();
            keyword1.value = DateTime.Now.ToShortDateString();
            keyword1.color = "#173177";

            WechatModelData keyword2 = new WechatModelData();
            keyword2.value = "日语";
            keyword2.color = "#173177";

            WechatModelData keyword3 = new WechatModelData();
            keyword3.value = DateTime.Now.ToShortDateString() + "作业";
            keyword3.color = "#173177";

            WechatModelData keyword4 = new WechatModelData();
            keyword4.value = work;
            keyword4.color = "#173177";

            WechatModelData remark = new WechatModelData();
            remark.value = "感谢您的查阅，请认真对待，按时完成作业。";
            remark.color = "#173177";

            WechatModelDataList list = new WechatModelDataList();
            list.first = first;
            list.keyword1 = keyword1;
            list.keyword2 = keyword2;
            list.keyword3 = keyword3;
            list.keyword4 = keyword4;
            list.remark = remark;

            wechatToken.wechatPushWork(openId, list);
        }
        #endregion

        #region 进行生成复杂字符串
        public string getRandomStr(int n)//b：是否有复杂字符，n：生成的字符串长度
        {
            string str = "0123456789";

            StringBuilder SB = new StringBuilder();
            Random rd = new Random();
            for (int i = 0; i < n; i++)
            {
                SB.Append(str.Substring(rd.Next(0, str.Length), 1));
            }
            return SB.ToString();
        }
        #endregion

        #region 获取作业列表
        public List<Work_Model> getWorkList()
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from work order by id desc";
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Work_Model> workList = new List<Work_Model>();
            for (int i = 0; i < rows; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string workName = dt.Rows[i]["workName"].ToString();
                string hasPush = dt.Rows[i]["hasPush"].ToString();
                string pushType = dt.Rows[i]["pushType"].ToString();
                string pushUser = dt.Rows[i]["pushUser"].ToString();
                string date = dt.Rows[i]["date"].ToString();
                string workId = dt.Rows[i]["linkId"].ToString();

                List<string> subWorkList = getWorkListWithLinkId(workId);
                Work_Model workModel = new Work_Model()
                {
                    id = id,
                    workName = workName,
                    hasPush = hasPush,
                    pushType = pushType,
                    pushUser = pushUser,
                    date = date,
                    linkId = workId,
                    workList = subWorkList,
                };
                workList.Add(workModel);
            }
            sqlcon.Close();
            return workList;
        }
        #endregion

        #region 根据link获取workList
        public List<string> getWorkListWithLinkId(string linkId) {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from work_sub where linkId = '"+linkId+"'";
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<string> workList = new List<string>();
            for (int i = 0; i < rows; i++)
            {
                string title = dt.Rows[i]["title"].ToString();
             
                workList.Add(title);
            }
            sqlcon.Close();
            return workList;
        }
        #endregion

        #region 根据学生id获取作业列表
        public List<Work_Model> getWorkListWithStudentIdManager(string studentId)
        { 
            // 1. 获取列表
            List<Work_Student_Model> work_studentList = getWorkListWithStudentId(studentId);
            // 2. 获取作业信息
            List<Work_Model> workList = new List<Work_Model>();
            for (int i = 0; i < work_studentList.Count; i++) {
                Work_Student_Model infoModel = work_studentList[i];
                Work_Model workModel = getWorkListWithWorkId(infoModel.linkId);
                workList.Add(workModel);
            }

            return workList;
        }


        public List<Work_Student_Model> getWorkListWithStudentId(string studentId)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from work_student where student_id = '"+studentId+"' order by id desc";
            //查询音乐信息
            DataTable dt = new DataTable();

            SqlDataAdapter dap = new SqlDataAdapter(strselect, sqlcon);
            dap.Fill(dt);
            int rows = dt.Rows.Count;

            List<Work_Student_Model> workStudentList = new List<Work_Student_Model>();
            for (int i = 0; i < rows; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string student_id = dt.Rows[i]["student_id"].ToString();
                string linkId = dt.Rows[i]["linkId"].ToString();
                string datetime = dt.Rows[i]["datetime"].ToString();
                Work_Student_Model workModel = new Work_Student_Model()
                {
                    id = id,
                    student_id = student_id,
                    linkId = linkId,
                    datetime = datetime,
                  
                };
                workStudentList.Add(workModel);
            }
            sqlcon.Close();
            return workStudentList;
        }
        #endregion

        #region 根据linkId获取到作业信息
        public Work_Model getWorkListWithWorkId(string linkId)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string strselect = "select * from work where linkId = '" + linkId + "'"; SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            Work_Model workModel = new Work_Model();
            if (dr.Read())
            {
                workModel.id = dr["id"].ToString();
                 workModel.workName = dr["workName"].ToString();
                 workModel.hasPush = dr["hasPush"].ToString();
                 workModel.pushType = dr["pushType"].ToString();
                 workModel.pushUser = dr["pushUser"].ToString();
                 workModel.date = dr["date"].ToString();
                 workModel.linkId = dr["linkId"].ToString();
                 workModel.workList = getWorkListWithLinkId(workModel.linkId);
            }
            sqlcon.Close();
            return workModel;

        }
        #endregion

    }
}